import 'dart:convert';
import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:dio/dio.dart';
import 'package:study1/model/v1user.dart';
import 'package:select_form_field/select_form_field.dart';
import 'package:fluttertoast/fluttertoast.dart';

class V1user_Add extends StatefulWidget {
  const V1user_Add({Key? key}) : super(key: key);

  @override
  _V1user_AddState createState() => _V1user_AddState();
}

class _V1user_AddState extends State<V1user_Add> {
  @override
  void initState() {
    super.initState();
    getdanwei();
  }

  Future<void> getdanwei() async {
    Dio dio = Dio();
    String url = "http://221.193.206.189:60000/admin/getv1danweilist";
    Map<String, dynamic> map = Map();
    map["username"] = _username;
    map["password"] = _password;
    map["nickname"] = _nickname;
    Response response = await dio.post(url, data: map);
    var data = jsonDecode(response.data);
    if (response.statusCode == 200) {
      print("响应数据:${response.data}");
      var listDynamic = jsonDecode(response.data);
      List<Map<String, dynamic>> listMap =
          new List<Map<String, dynamic>>.from(listDynamic);
      List<Map<String, dynamic>> M = [];

      listMap.forEach((element) {
        Map<String, dynamic> map = Map();
        map["value"] = element["id"];
        map["label"] = element["danweimingcheng"];
        M.add(map);
      });
      setState(() {
        _items = M;
      });
    }
  }

  GlobalKey<FormState> user_add_key = new GlobalKey<FormState>();
  String _username = "";
  String _password = "";
  String _nickname = "";
  String _danweiid = "";
  var _isShowClear = false;
  List<Map<String, dynamic>> _items = [
    {
      'value': '12',
      'label': '邯山',
      'icon': const Icon(Icons.stop),
    },
    {
      'value': '14',
      'label': '复兴',
      'icon': const Icon(Icons.fiber_manual_record),
      'textStyle': const TextStyle(color: Colors.red),
    },
    {
      'value': '15',
      'label': '肥乡',
      'enable': false,
      'icon': const Icon(Icons.grade),
    },
  ];

  Void? creatuser() {
    var form = user_add_key.currentState;
    if (form!.validate()) {
      form.save();
      post_creatuser();
    }
    return null;
  }

  void post_creatuser() async {
    Dio dio = Dio();
    String url = "http://221.193.206.189:60000/admin/addv1user";
    Map<String, dynamic> map = Map();
    map["username"] = _username;
    map["password"] = _password;
    map["nickname"] = _nickname;
    map["danweiid"] = _danweiid;
    for (var item in _items) {
      if (item["value"].toString() == _danweiid) {
        map["danweiminghcneg"] = item["label"];
        break;
      }
    }

    Response response = await dio.post(url, data: map);
    // var data = jsonDecode(response.data);
    if (response.statusCode == 200) {
      if (response.data.toString().startsWith("false")) {
        print("创建失败");
        Fluttertoast.showToast(
            msg: "创建用戶失敗,原因为"+response.data.toString(),
            gravity: ToastGravity.TOP,
            timeInSecForIosWeb: 2,
            textColor: Colors.green,
            fontSize: 14);
      } else {
        print("创建成功");
        Fluttertoast.showToast(msg: "创建用戶成功",
            gravity: ToastGravity.TOP,
            timeInSecForIosWeb: 2,
            textColor: Colors.green,
            fontSize: 20);

        Navigator.pop(context);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    print("打开 添加用户界面");
    return Scaffold(
      appBar: AppBar(
        title: Text("添加用户"),
      ),
      body: ListView(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: 20, right: 20),
            decoration: const BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(8)),
                color: Colors.white),
            child: Form(
                key: user_add_key,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    TextFormField(
                      // controller: _userNameController,
                      // focusNode: _focusNodeUserName,
                      //设置键盘类型
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                        labelText: "用户名",
                        hintText: "请输入用户号",
                        prefixIcon: Icon(Icons.person),
                        //尾部添加清除按钮
                        suffixIcon: (_isShowClear)
                            ? IconButton(
                                icon: Icon(Icons.clear),
                                onPressed: () {
                                  // 清空输入框内容
                                  // _userNameController.clear();
                                },
                              )
                            : null,
                      ),
                      //验证用户名
                      // validator: validateUserName,
                      //保存数据
                      onSaved: (String? value) {
                        _username = value!;
                      },
                    ),
                    TextFormField(
                      decoration: const InputDecoration(
                        hintText: "请输入密码",
                        labelText: "请输入密码",
                        prefixIcon: Icon(Icons.password),
                      ),
                      onSaved: (value) {
                        _password = value!;
                      },
                      onFieldSubmitted: (value) {},
                    ),
                    TextFormField(
                      decoration: const InputDecoration(
                        hintText: "请输入呢称",
                        labelText: "请输入呢称",
                        prefixIcon: Icon(Icons.supervised_user_circle),
                      ),
                      onSaved: (value) {
                        _nickname = value!;
                      },
                      onFieldSubmitted: (value) {},
                    ),
                    SelectFormField(
                        type: SelectFormFieldType.dropdown,
                        // or can be dialog
                        initialValue: 'circle',
                        icon: const Icon(Icons.format_shapes),
                        labelText: '所属单位',
                        items: _items,
                        onChanged: (val) => print(val),
                        onSaved: (val) => _danweiid = val!),
                  ],
                )),
          ),
          SizedBox(
            height: ScreenUtil().setHeight(20),
          ),
          SizedBox(
              width: ScreenUtil().setWidth(25),
              height: ScreenUtil().setHeight(100),
              child: Column(
                children: [
                  ElevatedButton(
                    style: ButtonStyle(),
                    onPressed: creatuser,
                    child: const Padding(
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
                        child: Text("创建用户")),
                  ),
                ],
              ))
        ],
      ),
    );
  }
}
